package com.szrt.dapartment.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.szrt.dapartment.dao.DepartmentDao;
import com.szrt.dapartment.enity.DepartmentEntity;
import com.szrt.util.JDBCUtil;

public class DepartmentDaoImpl implements DepartmentDao {

	@Override
	public int add(DepartmentEntity entity) {
		Connection connection = JDBCUtil.getConnection();
		String sql="INSERT INTO cgj_department_t VALUE(?,?)";
		int counter =0;
		PreparedStatement  statement = null;
		try {
			statement =connection.prepareStatement(sql);
			statement.setInt(1, entity.getDepartmentCode());
			statement.setString(2, entity.getDepartmentName());
			counter =statement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			if(null != statement){
				try {
					statement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(null != connection){
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return counter;
	}

	

	@Override
	public int delete(Integer code) {
		String sql="DELETE FROM cgj_department_t WHERE D_ID=1";
		Connection         connection = JDBCUtil.getConnection();
		PreparedStatement  statement = null;
		ResultSet          set = null;
		int counter=-1;
		try {
			
			//2得到执行语句  带sql


			statement =connection.prepareStatement(sql);
			
			
			//3 把问号中的东西设置好
			statement.setInt(1, code);
			
			//4执行查询
			counter =statement.executeUpdate();
			
			return counter;
		} catch (SQLException e) {
			e.printStackTrace();
			return counter;
		}finally{
			if(null != set){
				try {
					set.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				
			}
			if(null != statement){
				try {
					statement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				
			}
			if(null != connection){
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public Map<Integer, String> checkDepartment() throws Exception {
		Map<Integer, String> map=new HashMap<Integer, String>();
		Connection conn=JDBCUtil.getConnection();
		String sql="SELECT * FROM cgj_department_t";
		PreparedStatement ps=conn.prepareStatement(sql);
		ResultSet rs=ps.executeQuery();
		while(rs.next()){
			map.put(rs.getInt("D_ID"), rs.getString("D_NAME"));
		}
		if(null!=rs){
			rs.close();
		}
		if(null!=ps){
			ps.close();
		}
		if(null!=conn){
			conn.close();
		}
		return map;
	}

}
